package com.srwl.mytx.im.conversation;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.ConversationActivity.ContactNotifyActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.ConversationData;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.greendao.UserDao;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.MessageHandler;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.task.RequestLocationTask;

import java.util.ArrayList;
import java.util.List;

public class ContactNotifyConversation extends SystemNotifyConversation {
    private static final String TAG = "ContactMessageConversat";
    private ContactDao contactDao;
    private UserDao userDao;
    private List<String> locationTaskList;

    public ContactNotifyConversation(Context context, ConversationData data, MessageHandler messageHandler, MessageUnReadCountListener unReadCountListener) {
         super(context,data, messageHandler, unReadCountListener);

        contactDao = DBManager.getInstance().getDaoSession().getContactDao();
        userDao = DBManager.getInstance().getDaoSession().getUserDao();
    }


    @Override
    public void receivedMessage(Message message) {
        if (message == null) {
            return;
        }
        //添加联系人类型的消息，需要把id  设置为对方的用户id，这样方便收到同一个人的联系人消息的时候，可以覆盖之前的。
        message.setId(message.getFromId());
        Integer messageType = message.getSubType();
        switch (messageType) {
            case Constant.PUSH_MESSAGE_REQUEST_ADD_CONTACT:
                Log.i(TAG, "对方请求添加我为联系人:" + message.getFromId());
                message.setState(Constant.INVITE_MESSAGE_STATUS_APPLY);
                saveMessageAndRefreshView(message);

                break;
            case Constant.PUSH_MESSAGE_REFUSE_ADD_CONTACT:
                Log.i(TAG, "对方拒绝添加我的联系人添加请求:" + message.getFromId());
                message.setId(message.getFromId());
                message.setContent("对方已经拒绝您的联系人添加请求");
                saveMessageAndRefreshView(message);
                break;

            case Constant.PUSH_MESSAGE_DELETE_CONTACT:
                Log.i(TAG, "对方把我删除了:" + message.getFromId());
                onReceivedDeleteContactNotify(message);
                break;
            case Constant.PUSH_MESSAGE_ACCEPT_ADD_CONTACT:
                Log.i(TAG, "对方接受我的联系人添加请求" + message.getFromId());
                onAcceptAddContact(message);
                break;

            case Constant.PUSH_MESSAGE_CONTACT_INFO_CHANGE:
                Log.i(TAG, "对方更新联系人信息了:" + message.toString());//比如给我的权限更新了
                if (message.getExtraData() != null) {
                    Contact contact = JSONObject.parseObject(message.getExtraData(), Contact.class);
                    updateContact(contact);
                }
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));

                break;

            case Constant.PUSH_MESSAGE_CONTACT_USER_INFO_CHANGE:
                Log.i(TAG, "对方更新用户信息了:" + message.toString());
                if (message.getExtraData() == null) {
                    return;
                }
                //greenDao 没有类似mybatis 的根据字段的存在与否，更新部分字段的***selective方法，
                User user = JSONObject.parseObject(message.getExtraData(), User.class);
                User fullUpdateUser = updateUser(user);
                Helper.getInstance().refreshCache();
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));
                Conversation c2cConversation = IMSClientBootstrap.getInstance().getConversationService().getExistC2cConversation(user.getuId());
                if (c2cConversation != null) {
                    c2cConversation.onTargetUserInfoChange(fullUpdateUser);
                }
                break;
            case Constant.PUSH_MESSAGE_LOCATION_REQUEST: {
                Log.i(TAG, "收到定位请求:" + message.toString());

                if (message.getExtraData() == null) {
                    return;
                }
                if (locationTaskList == null) {
                    locationTaskList = new ArrayList<>();
                }
                Contact contact = JSONObject.parseObject(message.getExtraData(), Contact.class);
                String cid = contact.getCId();
                if (TextUtils.isEmpty(cid)) {
                    return;
                }
                if (locationTaskList.contains(cid)) {
                    Log.i(TAG, "这个是重复的定位请求:" + cid);
                    return;
                }
                onReceivedLocationRequest(contact, cid);
                break;
            }

            case Constant.PUSH_MESSAGE_LOCATION_RESULT:
                Log.i(TAG, "收到定位结果:" + message.toString());
                User locationResult;
                if (message.getExtraData() != null) {
                    locationResult = JSONObject.parseObject(message.getExtraData(), User.class);
                } else {
                    return;
                }
                Intent intent = new Intent(Constant.ACTION_RESULT_LOCATION);
                Bundle bundle = new Bundle();
                bundle.putParcelable(EaseConstant.EXTRA_TARGET_USER, locationResult);
                intent.putExtras(bundle);
                broadcastManager.sendBroadcast(intent);
                break;
            default:
                Log.e(TAG, "receivedMessage: 有消息未类型未处理" + message.toString());
        }


    }

    private void onAcceptAddContact(Message message) {
        if (message.getExtraData() == null) {
            return;
        }
        Contact contact = JSONObject.parseObject(message.getExtraData(), Contact.class);
        User targetUser = contact.getUser();
        if (targetUser == null) {
            return;
        }
        //保存联系人
        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(targetUser);
        contact.settId(targetUser.getuId());//补全用户id,否则无法实现Contact 表和User表的关联
        contactDao.insertOrReplace(contact);
        //广播，联系人变动，刷新联系人列表
        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));
        //本来是一条推送的消息，现在改装为一条 C2C文本消息，并作为本地消息发给自己
        message.setContent(context.getString(R.string.add_contact_complete));
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_TEXT);
        IMSClientBootstrap.getInstance().sendLocalMessage(message);
    }


    private void onReceivedDeleteContactNotify(Message message) {
        //对方把我删除了，我这边只更新状态，并不真的删除对方
        if (message.getExtraData() != null) {
            Contact contact = JSONObject.parseObject(message.getExtraData(), Contact.class);
            updateContact(contact);
        }
        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));

        //查看在个人设置中，好友关系解除的时候是否需要通知
        if (Helper.getInstance().getModel().getSettingDeleteMsgNotify()) {
            String fromId = message.getFromId();
            message.setId(fromId);
            User targetUser = Helper.getInstance().getContactUserInfo(fromId);
            if (targetUser != null) {
                message.setTitle(targetUser.getUsername());
                message.setIcon(targetUser.getAvatar());
            }
            message.setContent("对方已经解除和你的好友关系");
            saveMessageAndRefreshView(message);
        }

    }

    /**
     * 当收到 位置信息请求
     *
     * @param contact
     * @param cid
     */
    private void onReceivedLocationRequest(Contact contact, String cid) {
        //获取当前登录的用户id
        String loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
        Contact localContact = contactDao.load(cid);
        if (localContact == null) {
            Log.e(TAG, "onReceivedLocationRequest: 对方请求我的位置信息，并不在我的联系人中，，" + contact.toString());
            return;
        }
        //在本地再检查 对方是否有权限查看我的位置
        //判断当前登录的用户是否为主动添加方
        if (TextUtils.equals(loginUserId, localContact.getmId())) {
            //如果当前用户是主动添加方,根据tLocation判断我是否给对方权限
            if (TextUtils.equals(localContact.getcId(), cid) && TextUtils.equals(localContact.getTLocation(), Constant.CONTACT_HAVE_AUTHORITY)) {
                locationTaskList.add(cid);
                //通知收到查询位置请求
                contact.settId(localContact.getTargetUser().getuId());
                RequestLocationTask instance = new RequestLocationTask(contact, context);
                instance.setLocationListener(new RequestLocationTask.LocationListener() {
                    @Override
                    public void onLocationSuccess(String contactId) {
                        locationTaskList.remove(contactId);
                    }
                });
                instance.execute(context);
            }
        } else {
            //如果当前用户是被动添加方,根据location判断我是否给对方权限
            if (TextUtils.equals(localContact.getcId(), cid) && TextUtils.equals(localContact.getLocation(), Constant.CONTACT_HAVE_AUTHORITY)) {
                locationTaskList.add(cid);
                //通知收到查询位置请求
                contact.settId(localContact.getTargetUser().getuId());
                RequestLocationTask instance = new RequestLocationTask(contact, context);
                instance.setLocationListener(new RequestLocationTask.LocationListener() {
                    @Override
                    public void onLocationSuccess(String contactId) {
                        locationTaskList.remove(contactId);
                    }
                });
                instance.execute(context);
            }
        }
    }

    private void updateContact(Contact contact) {
        boolean bol_updateSuccess = false;
        List<Contact> contactList = contactDao.loadAll();
        for (Contact originalContact : contactList) {
            if (TextUtils.equals(originalContact.getcId(), contact.getcId())) {
                //更新定位权限
                if (contact.getLocation() != null) {
                    originalContact.setLocation(contact.getLocation());
                }
                if (contact.getTLocation() != null) {
                    originalContact.setTLocation(contact.getTLocation());
                }
                //更新轨迹权限
                if (contact.getTrace() != null) {
                    originalContact.setTrace(contact.getTrace());
                }
                //更新 亲戚互联权限
                if (contact.getRelationInfinite() != null) {
                    originalContact.setRelationInfinite(contact.getRelationInfinite());
                }
                if (contact.getTRelationInfinite() != null) {
                    originalContact.setTRelationInfinite(contact.getTRelationInfinite());
                }
                //更新 联系人状态
                if (contact.getStatus() != null) {
                    originalContact.setStatus(contact.getStatus());
                }
                //后续有更多更新字段，在这添加，可可以考虑用反射写一个通用的赋值工具类
                contactDao.update(originalContact);
                bol_updateSuccess = true;
            }
        }
        if (!bol_updateSuccess) {//如果没更新到，那就直接插入
            contactDao.insertOrReplace(contact);
        }
    }


    private User updateUser(User targetUser) {
        User originalUserInfo = userDao.load(targetUser.getuId());
        if (originalUserInfo == null) {
            return null;
        }
        if (targetUser.getUsername() != null) {
            originalUserInfo.setUsername(targetUser.getUsername());
        }
        if (targetUser.getAvatar() != null) {
            originalUserInfo.setAvatar(targetUser.getAvatar());
        }
        if (targetUser.getPhone() != null) {
            originalUserInfo.setPhone(targetUser.getPhone());
        }
        if (targetUser.getArea() != null) {
            originalUserInfo.setArea(targetUser.getArea());
        }
        if (targetUser.getGender() != null) {
            originalUserInfo.setGender(targetUser.getGender());
        }
        if (targetUser.getNick() != null) {
            originalUserInfo.setNick(targetUser.getNick());
        }

        userDao.update(originalUserInfo);

        return originalUserInfo;
    }

    /**
     * 系统推送消息未读数，以消息表中查询出来的数量为准，而不是 ConversationData 中记录的未读数
     * 因为推送消息存在覆盖的问题，比如同一个人发送的添加联系人请求，就算重复发送，在message 中，也只会存在一条数据，
     */
    protected void queryUnReadCount() {
        //每次保存消息后，都重新读取通知类型的消息未读数量，因为推送类型的消息id,可能是重复的（比如和某一个人的添加联系人相关的消息或者是某个悬赏主题的任务通知消息），
        // 也许某条信息还是未读状态，就被覆盖了，只有去数据库读取未读数，才能保证正确的通知类型消息的未读总数
        int newUnReadCount = messageHandler.queryUnreadCount(Constant.CONVERSATION_TYPE_CONTACT + "");
        if (newUnReadCount > unReadCount && unReadCountListener != null) {
            unReadCountListener.onReadCountAdd(newUnReadCount - unReadCount);
            Log.d(TAG, "saveNotify: 联系人推送消息未读数增加" + (newUnReadCount - unReadCount));
            unReadCount = newUnReadCount;
        } else if (newUnReadCount < unReadCount && unReadCountListener != null) {
            unReadCountListener.onReadCountReduce(unReadCount - newUnReadCount);
            Log.d(TAG, "saveNotify: 联系人推送消息未读数减少" + (unReadCount - newUnReadCount));
            unReadCount = newUnReadCount;
        }
    }


    public String getTitle() {

        return "联系人通知";
    }


    @Override
    public int getIconResourceId() {
        return R.drawable.tx_contact_icon;
    }

    public String getContent() {
        if (lastMessage.getSubType() == Constant.PUSH_MESSAGE_REQUEST_ADD_CONTACT) {
            return "请求添加联系人";
        }
        return lastMessage.getContent();
    }

    /**
     * 打开通知页面
     *
     * @param context
     */
    public void openConversation(Context context) {
        if (unReadCount > 0) {

            if (unReadCountListener != null) {
                unReadCountListener.onReadCountReduce(unReadCount);
            }
            messageHandler.setMessageReadByConversationId(cId);
            unReadCount = 0;
        }
        context.startActivity(new Intent(context, ContactNotifyActivity.class));
    }
}
